﻿using mode;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Weave.Server;

namespace autoupServer
{
    class Program
    {
        static  WeaveP2Server p2Server = new WeaveP2Server(Weave.Base.WeaveDataTypeEnum.Bytes);
        static void Main(string[] args)
        {
            int port =Convert.ToInt32( System.Configuration.ConfigurationSettings.AppSettings["prot"]);
            p2Server.weaveReceiveBitEvent += P2Server_weaveReceiveBitEvent;
            p2Server.Start(port);
        }


        static string[] getfiles(string path,string pre)
        {
            List<String> listfile = new List<string>();
           string [] Directs=   System.IO.Directory.GetDirectories(path);

            foreach (string dir in Directs)
            { 
                listfile.AddRange(getfiles(dir, pre));
            }
            string[] files = System.IO.Directory.GetFiles(path);
            for(var i = 0; i < files.Length; i++)
            { 
                string temp = files[i].Replace(pre, ""); 
                listfile.Add(temp);
            }
            return listfile.ToArray();
        }
        static byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 
          
            return bytes;
        }
        private static void P2Server_weaveReceiveBitEvent(byte command, byte[] data, System.Net.Sockets.Socket soc)
        {
            try
            {
                switch (command)
                {

                    case 0x01:
                        string json = System.Text.Encoding.UTF8.GetString(data);
                        prjversion prj = Newtonsoft.Json.JsonConvert.DeserializeObject<prjversion>(json);
                        string[] paths = System.IO.Directory.GetDirectories(@"version\" + prj.name);
                        List<int> versions = new List<int>();
                        for (var i = 0; i < paths.Length; i++)
                        {
                            //\
                            int temp = Convert.ToInt32(paths[i].Substring(paths[i].LastIndexOf(@"\") + 1));
                            if (temp > prj.version)
                                versions.Add(temp);
                        }
                        string str = JsonConvert.SerializeObject(versions.ToArray());
                        p2Server.Send(soc, 0x01, str);
                        break;
                    case 0x02:
                        json = System.Text.Encoding.UTF8.GetString(data);
                        prj = Newtonsoft.Json.JsonConvert.DeserializeObject<prjversion>(json);
                        string path = @"version\" + prj.name + @"\" + prj.version; 
                        string [] filename=getfiles(path, path);
                         str = JsonConvert.SerializeObject(filename);
                        p2Server.Send(soc, 0x02, str);
                        break;
                    case 0x03:
                        json = System.Text.Encoding.UTF8.GetString(data);
                        prj = Newtonsoft.Json.JsonConvert.DeserializeObject<prjversion>(json);
                        if (System.IO.File.Exists(@"version\" + prj.name + @"\" + prj.version  + prj.file))
                        {
                           
                            String name = @"version\" + prj.name + @"\" + prj.version  + prj.file; 
                            FileStream fstream = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            long count = fstream.Length % (1024 * 4) == 0 ? fstream.Length / (1024 * 4) : (fstream.Length / (1024 * 4)) + 1;
                            int i = 0;
                            fstream.Position = 0;
                            filestream fs = new filestream();
                            fs.Filename = prj.file;
                            fs.Index = 0;
                            fs.Len = 0;
                            fs.Stream = null;
                            fs.Maxlen = fstream.Length; 
                            fstream.Close();
                            str = JsonConvert.SerializeObject(fs);
                            p2Server.Send(soc, 0x03, str);
                        }
                        else
                           p2Server.Send(soc, 0xfb, "不存在的内容");
                        break;
                    case 0x04:
                        json = System.Text.Encoding.UTF8.GetString(data);
                        prj = Newtonsoft.Json.JsonConvert.DeserializeObject<prjversion>(json);
                        if (System.IO.File.Exists(@"version\" + prj.name + @"\" + prj.version + prj.file))
                        {
                            String name = @"version\" + prj.name + @"\" + prj.version + prj.file;
                            FileStream fstream = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            long count = fstream.Length % (1024 * 4) == 0 ? fstream.Length / (1024 * 4) : (fstream.Length / (1024 * 4)) + 1;
                            int i = 0;
                            fstream.Position = 0;
                           
                            filestream fs = new filestream();  
                            while (i < count)
                            {
                                //创建一个容量4K的数组
                                byte[] byteData = new byte[1024 * 4];
                                //从文件中读取数据写入到数组中(数组对象，从第几个开始读，读多少个)
                                //返回读取的文件内容真实字节数
                                int length = fstream.Read(byteData, (int)0, byteData.Length);
                                //如果字节数大于0，则转码
                                if (length > 0)
                                {
                                    MemoryStream ms = new MemoryStream();
                                    ms.Position = 0;
                                    BinaryWriter br = new BinaryWriter(ms);
                                    br.Write(i);
                                    br.Write(length);
                                    br.Write(byteData);
                                    p2Server.Send(soc, 0x04, StreamToBytes(br.BaseStream));
                                    br.Close();
                                    ms.Close();
                                }
                                else { fstream.Close(); return; }
 
                                i++;
                            }
                        }
                        else
                            p2Server.Send(soc, 0xfb, "不存在的内容");
                        break;
                    case 0x05:
                        json = System.Text.Encoding.UTF8.GetString(data);
                        prj = Newtonsoft.Json.JsonConvert.DeserializeObject<prjversion>(json);
                         path = @"version\" + prj.name + @"\" + prj.version + prj.file;
                        if (System.IO.File.Exists(path))
                        {
                          //  filestream fstre = _0x01.GetRoot<filestream>();
                            byte[] byteData = new byte[1024 * 4];
                            //从文件中读取数据写入到数组中(数组对象，从第几个开始读，读多少个)
                            //返回读取的文件内容真实字节数
                            FileStream fstream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                            fstream.Seek(prj.index * 1024 * 4, SeekOrigin.Begin);
                            int length = fstream.Read(byteData, (int)0, byteData.Length);
                            //如果字节数大于0，则转码
                            if (length > 0)
                            {
                                MemoryStream ms = new MemoryStream();
                                ms.Position = 0;
                                BinaryWriter br = new BinaryWriter(ms);
                                br.Write(prj.index);
                                br.Write(length);
                                br.Write(byteData);
                                p2Server.Send(soc, 0x04, StreamToBytes(br.BaseStream));
                                br.Close();
                                ms.Close(); 
                            }
                        }
                        else
                            p2Server.Send(soc, 0xfb, "不存在的内容");
                        break;
                    default:
                        break;

                }
            }
            catch(Exception e) {
                p2Server.Send(soc, 0xfb, "错误的数据或服务器异常");

            }
        }
    }
}
